<?php

class auth
{
    var $def_redir = 'monitor.php';
    var $def_auth = 'auth.php';
    var $auth_type_ = 0;            // 0 - monitor 1-admin

    var $auth_role_user = 0;
    var $auth_role_disp = 1;
    var $auth_role_eng  = 2;
    var $auth_role_adm  = 3;

    var $auth_can_login_admin = array(2,3); // why can login in admin int

    var $cookie_name = 'AuthAsud2';
    var $sessid = '';

    function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') 
    { 
        $str = ''; 
        $count = strlen($charset); 
        while ($length--) 
        { 
            $str .= $charset[mt_rand(0, $count-1)]; 
        } 
        return $str; 
    } 

    function explainRole($_role)
    {
        switch($_role)
        {
            case $this->auth_role_user:
                return "Наблюдатель";
            case $this->auth_role_disp:
                return "Диспетчер";
            case $this->auth_role_eng:
                return "Инженер";
            case $this->auth_role_adm:
                return "Администратор";
        }
    }

    function setDefRedir($_redir)
    {
        $this->def_redir = $_redir;
    }

    function authentication($dbh, $post)
    {
        if (isset($post['login']) && isset($post['password']) && isset($post['submit']))
        {

            $sth = $dbh->prepare('select * from users where login=:login and password=PASSWORD(:password) LIMIT 1');

            if ($sth->execute(array(':login' => rtrim(ltrim(addslashes($post['login']))),
                                ':password' => rtrim(ltrim(addslashes($post['password']))) )))
            {
                $alldb = $sth->fetchAll(PDO::FETCH_ASSOC); 

                if (empty($alldb))
                    return false;
                
                $user['login'] = $alldb[0]['login'];
                $user['name'] = $alldb[0]['name'];
                $user['role'] = $alldb[0]['role'];

                $this->sessid = $this->randString(10);

                try
                {
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $dbh->beginTransaction();

                    try
                    {
                        $sth = $dbh->prepare('delete from session where last_login < DATE_SUB(NOW(), INTERVAL 1 WEEK) or idsession = ?'); // renew all session data

                        $sth->execute(array($this->sessid));
                    }
                    catch (Exception $e)
                    {
                            // ok no active session
                    }

                    $sth = $dbh->prepare('insert into session (idsession, session_data, last_login) values (?,?,NOW())');
                    $sth->execute(array($this->sessid, base64_encode(serialize($user))));

                    $sth = $dbh->prepare('insert into log (log_date,log_type, imp, user,log_msg) values (NOW(),0,0,:user,"Оператор вошел в систему")');
                    $sth->execute(array('user'=> $user['login']));

                    $dbh->commit();


                }
                catch (Exception $e)
                {
                    $dbh->rollBack();
                    return false;
                }

                return true;
            }
            else                                                   
            {
                return false;
            }
        }
    }

    function getRedir()
    {
        return 'Location: ' . $this->def_redir;
    }

    function getAuthRedir()
    {
        return 'Location: ' . $this->def_auth.'?redir=' . $this->def_redir;
    }

    function getCookie()
    {
        $cookie['name'] = $this->cookie_name;
        $cookie['value'] = $this->sessid;
        return $cookie;
    }

    function getSessId()
    {
        return $this->sessid;
    }

    function isauth($dbh, $cookies, $admin = true)
    {
        if (isset($cookies[$this->cookie_name]))
        {
            $this->sessid = $cookies[$this->cookie_name];

            $sth = $dbh->prepare('select * from session where idsession=:sessid limit 1');

            if ($sth->execute(array(':sessid' => $this->sessid)))
            {
                
                $alldb = $sth->fetchAll(PDO::FETCH_ASSOC);

                if (empty($alldb))
                    return false;

                $user_info = unserialize(base64_decode($alldb[0]['session_data']));

                $sth = $dbh->prepare('select name, role from users where login=:login limit 1');

                if ($sth->execute(array(':login' => $user_info['login']))) 
                {
                    $alldb = $sth->fetchAll(PDO::FETCH_ASSOC); 

                    if (empty($alldb))          // user has been deleted 
                    {
                        return false;
                    }
                
                    $user['name'] = $alldb[0]['name'];  // renew info and role
                    $user['role'] = $alldb[0]['role'];
                }

                if ($admin && (in_array(intval($user_info['role']), $this->auth_can_login_admin) == FALSE))
                {
                    return false;
                }

                return $user_info;
            }
        }

        $this->sessid = '';
        return false;
    }
}

?>
